import 'dart:async';

import 'package:get/get.dart';
import 'package:tiktokadult/config/config.dart';
import 'package:tiktokadult/hj_page/pre_sale/pre_sale_provider.dart';
import 'package:tiktokadult/tools_base/global_store/store.dart';

import '../../hj_model/home/home_tabs_entity.dart';
import '../../tools_base/event_bus/event_bus_util.dart';
import '../../tools_base/event_bus/events.dart';
import '../cartoon_business/cartoon_sub_module_logic.dart';
import '../cartoon_business/cartoon_sub_module_page.dart';
import '../community_business/community/community_module_logic.dart';
import '../community_business/community_main_page_page/community_main_logic.dart';
import '../home_business/home_main_logic.dart';
import '../short_video/short_video_main_logic.dart';
import 'main_page_state.dart';
import 'main_page_view.dart';
import 'provider/msg_provider.dart';

class ModuleModel {
  /// 对应的底部tab
  int? mainM;

  /// 对应的顶部tab
  int? fatherM;

  /// 顶部tab对应的呀模块
  int? module;
  ModuleModel({this.mainM, this.fatherM, this.module});
}

class MainPageLogic extends GetxController with GetTickerProviderStateMixin {
  final MainPageState state = MainPageState();

  Rx<String?> darkInitTabId = Rx<String?>(null); // 暗网默认亚模块 id
  RxInt communityIndex = 0.obs; // 社区模块默认模块
  RxInt communitySubIndex = 0.obs; // 社区模块默认亚模块
  int acgIndex = 0;
  int acgTabIndex = 0;
  late StreamSubscription yinnserSubscription;
  late StreamSubscription loginSubScription;

  /// 亚模块id -<主>tab - <模块 - 亚模块>
  final moduleMap = <String, ModuleModel>{};
  @override
  void onInit() {
    super.onInit();
    MineMsgProvider().loadData();

    yinnserSubscription = eventBus.on<YinseinnerModel>(eventBusCallback);
    loginSubScription = eventBus.on<ReLoginEvent>(reLoginEvent);
    homeListTabDataCache.clear();

    /// 组装所有
    Future(() {
      final app = Config.plateModule;
      if (app == null) return;
      app.videosUI.asMap().forEach((k, v) {
        moduleMap[v.id ?? ''] = ModuleModel(mainM: 1, fatherM: 0, module: k);
      });
      app.deepWeb?.asMap().forEach((k, v) {
        moduleMap[v.id ?? ''] = ModuleModel(mainM: 3, fatherM: 0, module: k);
      });
      app.community?.asMap().forEach((k, v) {
        moduleMap[v.id ?? ''] = ModuleModel(mainM: 4, fatherM: 0, module: k);
      });
      app.picsUi.asMap().forEach((k, v) {
        moduleMap[v.id ?? ''] = ModuleModel(mainM: 2, fatherM: 4, module: k);
      });
      app.gameUi.asMap().forEach((k, v) {
        moduleMap[v.id ?? ''] = ModuleModel(mainM: 2, fatherM: 1, module: k);
      });
      app.novel?.asMap().forEach((k, v) {
        moduleMap[v.id ?? ''] = ModuleModel(mainM: 2, fatherM: 2, module: k);
      });
      app.audio?.asMap().forEach((k, v) {
        moduleMap[v.id ?? ''] = ModuleModel(mainM: 2, fatherM: 3, module: k);
      });
    });
  }

  void reLoginEvent(value) {
    backToRootRoute();
    jumpToPage(0);
    globalStore.refreshWallet();
    MineMsgProvider().loadData();
    presaleProvider.refreshPreSalStatus(); //刷新预售权益
    if (Get.isRegistered<HomeMainLogic>(tag: "HomeMainLogic")) {
      HomeMainLogic homeLogic = Get.find<HomeMainLogic>(tag: "HomeMainLogic");
      homeLogic.tabController?.index = 0;
    }
  }

  void eventBusCallback(YinseinnerModel model) {
    if (model.routeName == "navigation_bar") {
      //导航栏 亚模块菜单弹出
      pushToHomeNavBar();
    } else if (model.routeName == "module") {
      matchModuleById(model.id); // 媒体库亚模块分类
    } else if (model.routeName == "community_module") {
      matchModuleById(model.id); // 媒体库亚模块分类
    } else if (model.routeName == 'live_streaming') {
      backToRootRoute(); // 直播
      skipToLive();
    } else {}
  }

  void pushToHomeNavBar() {
    jumpToPage(0);
    if (Get.isRegistered<HomeMainLogic>(tag: "HomeMainLogic")) {
      HomeMainLogic homeLogic = Get.find<HomeMainLogic>(tag: "HomeMainLogic");
      homeLogic.openDrawer();
    }
  }

  //跳转直播
  void skipToLive() {
    jumpToPage(1);
    if (Get.isRegistered<ShortVideoMainLogic>()) {
      ShortVideoMainLogic shortLogic = Get.find<ShortVideoMainLogic>();
      shortLogic.jumpToLive();
    }
  }

  matchModuleById(String? id) {
    if (id == null) return;
    final moduleM = moduleMap[id];
    if (moduleM == null) return;
    if (moduleM.mainM == 0) {
      if (Get.isRegistered<HomeMainLogic>(tag: "HomeMainLogic")) {
        HomeMainLogic homeLogic = Get.find<HomeMainLogic>(tag: "HomeMainLogic");
        homeLogic.gotoTabId(id); // 首页和暗网 tab可自动排序, 不用 HomeModuleProvider处理
      }
      jumpToPage(0);
      return;
    }
    if (moduleM.mainM == 2) {
      //首页和暗网 tab可自动排序, 不用 HomeModuleProvider处理
      if (Get.isRegistered<HomeMainLogic>(tag: "HomeMainLogic_dark")) {
        HomeMainLogic homeLogic = Get.find<HomeMainLogic>(tag: "HomeMainLogic_dark");
        homeLogic.gotoTabId(id);
      } else {
        darkInitTabId.value = id;
      }
      jumpToPage(2);
      return;
    }
    if (moduleM.mainM == 3) {
      communityModuleEvent(moduleM);
      jumpToPage(3);
      return;
    }
  }

  void communityModuleEvent(ModuleModel moduleM) {
    if (Get.isRegistered<CommunityMainLogic>()) {
      CommunityMainLogic logic = Get.find<CommunityMainLogic>();
      int index = moduleM.fatherM ?? 0;
      int tabIndex = moduleM.module ?? 0;
      logic.jumpSubModule(index);
      if (index == 0) {
        if (Get.isRegistered<CommunityMainModuleLogic>()) {
          CommunityMainModuleLogic logic = Get.find<CommunityMainModuleLogic>();
          logic.skipToTabIndex(tabIndex);
          return;
        }
      } else {
        List<String> logicTagArr = ["", CommunityType.Pic.toString(), CommunityType.Game.toString(), CommunityType.TextNovel.toString()];
        if (Get.isRegistered<CartoonSubModuleLogic>(tag: logicTagArr[index])) {
          CartoonSubModuleLogic logic = Get.find<CartoonSubModuleLogic>(tag: logicTagArr[index]);
          logic.skipToTabIndex(tabIndex);
          return;
        }
      }
    }
    communityIndex.value = moduleM.fatherM ?? 0;
    communitySubIndex.value = moduleM.module ?? 0;
  }

  void backToRootRoute() {
    Get.until((route) {
      if (route.settings.name == MainPage.routeName) return true;
      return false;
    });
  }

  void jumpToPage(int index, {int? subIndex, int? subSubIndex}) {
    state.pageController.jumpToPage(index);
    if (index == 0) {
      // 刷新预售配置
      PreSaleProvider().refreshPreSaleConfig();
    }
  }

  @override
  void onClose() {
    yinnserSubscription.cancel();
    eventBus.off(yinnserSubscription);
    loginSubScription.cancel();
    eventBus.off(loginSubScription);
    super.onClose();
  }
}
